package com.yungu.swift.admin.utils;

import com.yungu.swift.base.ResponseData;
import com.yungu.swift.utils.JsonUtils;
import com.yungu.swift.utils.Md5Utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.*;

import static com.yungu.swift.admin.config.NacosListener.SYS_CONFIG;

/**
 * 上传工具类（上传到文件服务器）
 *
 * @author Zerrion
 * @since 2018/4/26.
 */
@Slf4j
@Component
public class UploadUtils {

    /**
     * 签名加密密钥
     */
    private final static String AUTH_KEY = "fffa2a879e62e198924a95dc150dc33823bd0bf7abd3a20fff605f297ae9333804699723a6219048";

    private static final String UPLOAD_IMAGE_API = "/api/v1/upload/image";
    private static final String UPLOAD_FILE_API = "/api/v1/upload/file";

    public static ResponseData<String> uploadImage(MultipartFile multipartFile, String appid, String mobile, String imageType) {
        return uploadByAPI(multipartFile, UPLOAD_IMAGE_API, appid, mobile, imageType);
    }

    public static ResponseData<String> uploadFile(MultipartFile multipartFile, String appid, String mobile) {
        return uploadByAPI(multipartFile, UPLOAD_FILE_API, appid, mobile, "");
    }

    private static ResponseData<String> uploadByAPI(MultipartFile multipartFile, String apiUrl, String appid, String mobile, String imageType) {
        try {
            String url = SYS_CONFIG.getApiHost() + apiUrl;
            HttpClient httpClient = HttpClientBuilder.create().build();
            HttpPost httpPost = new HttpPost(url);
            Map<String, String> map = new HashMap<>(8);
            map.put("noncestr", String.valueOf(new Random().nextInt(10000)));
            map.put("appid", appid);
            map.put("mobile", mobile);
            map.put("imageType", imageType);
            map.put("sign", signBuild(map));
            //初始化builder
            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            multipartEntityBuilder.setCharset(Charset.forName("UTF-8"));
            ContentType contentType = ContentType.create("text/plain", Charset.forName("UTF-8"));
            //加入文件部分
            File file = new File("/tmp/" + multipartFile.getOriginalFilename().replaceAll("[\\u4e00-\\u9fa5]", ""));
            IOUtils.copy(multipartFile.getInputStream(), new FileOutputStream(file));
            FileBody fileBody = new FileBody(file);
            multipartEntityBuilder.addPart("file", fileBody);
            //加入参数部分
            for (String key : map.keySet()) {
                multipartEntityBuilder.addPart(key, new StringBody(map.get(key), contentType));
            }
            httpPost.setEntity(multipartEntityBuilder.build());
            //执行请求
            HttpResponse response = httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity httpEntity = response.getEntity();
                HttpEntity entity = response.getEntity();
                String result = EntityUtils.toString(httpEntity);
                EntityUtils.consume(entity);
                return JsonUtils.readValue(result, ResponseData.class);
            }
        } catch (IOException e) {
            log.error("图片上传异常，fileName：{}", multipartFile.getOriginalFilename(), e);
        }
        return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "图片上传通讯异常");
    }


    private static String signBuild(Map<String, String> map) {
        StringBuilder sb = new StringBuilder();
        List<String> keyList = new ArrayList<String>(map.keySet());
        Collections.sort(keyList);
        for (int i = 0; i < keyList.size(); i++) {
            String key = keyList.get(i);
            String value = map.get(key);
            sb.append(i == 0 ? "" : "&").append(key).append("=").append(value);
        }
        sb.append("&key=" + AUTH_KEY);
        return Md5Utils.encode(sb.toString());
    }


}
